<template>
  <div class="calendar-container">
    <VCard>
      <VCardTitle class="d-flex align-center justify-space-between">
        <span>预约日历</span>
        <div class="d-flex align-center">
          <VBtn icon="mdi-chevron-left" @click="previousMonth" variant="text" />
          <span class="mx-4 text-h6">{{ currentMonthYear }}</span>
          <VBtn icon="mdi-chevron-right" @click="nextMonth" variant="text" />
        </div>
      </VCardTitle>
      <VCardText>
        <div class="calendar-grid">
          <div class="calendar-header">
            <div v-for="day in weekDays" :key="day" class="day-header">
              {{ day }}
            </div>
          </div>
          <div class="calendar-body">
            <div 
              v-for="date in calendarDates" 
              :key="date.key"
              :class="[
                'date-cell',
                { 'other-month': !date.isCurrentMonth },
                { 'today': date.isToday },
                { 'has-appointment': date.hasAppointment }
              ]"
              @click="selectDate(date)"
            >
              <div class="date-number">{{ date.day }}</div>
              <div v-if="date.hasAppointment" class="appointment-indicator">
                <VIcon size="12" color="primary">mdi-circle</VIcon>
              </div>
            </div>
          </div>
        </div>
      </VCardText>
    </VCard>

    <!-- 预约详情弹窗 -->
    <VDialog v-model="showAppointmentDialog" max-width="500px">
      <VCard>
        <VCardTitle>
          {{ selectedDate ? formatDate(selectedDate) : '' }} 的预约
        </VCardTitle>
        <VCardText>
          <div v-if="selectedDateAppointments.length > 0">
            <VList>
              <VListItem v-for="appointment in selectedDateAppointments" :key="appointment.id">
                <VListItemTitle>{{ appointment.studentName }}</VListItemTitle>
                <VListItemSubtitle>
                  {{ appointment.time }} - {{ appointment.type }}
                </VListItemSubtitle>
                <template #append>
                  <VChip 
                    :color="getAppointmentColor(appointment.status)" 
                    size="small"
                  >
                    {{ appointment.status }}
                  </VChip>
                </template>
              </VListItem>
            </VList>
          </div>
          <div v-else class="text-center py-4">
            <VIcon size="48" color="grey">mdi-calendar-blank</VIcon>
            <div class="mt-2 text-body-2">该日期暂无预约</div>
          </div>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn color="secondary" @click="showAppointmentDialog = false">关闭</VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';

// 状态管理
const currentDate = ref(new Date());
const selectedDate = ref<Date | null>(null);
const showAppointmentDialog = ref(false);

// 示例预约数据
const appointments = ref([
  {
    id: 1,
    date: new Date(2024, 11, 15),
    time: '09:00',
    studentName: '张三',
    type: '初访',
    status: '已确认'
  },
  {
    id: 2,
    date: new Date(2024, 11, 16),
    time: '14:00',
    studentName: '李四',
    type: '复诊',
    status: '待确认'
  },
  {
    id: 3,
    date: new Date(2024, 11, 20),
    time: '10:30',
    studentName: '王五',
    type: '初访',
    status: '已确认'
  }
]);

// 计算属性
const currentMonthYear = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth() + 1;
  return `${year}年${month}月`;
});

const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

const calendarDates = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth();
  
  // 获取当月第一天和最后一天
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  
  // 获取日历网格开始日期（包含上个月的日期）
  const startDate = new Date(firstDay);
  startDate.setDate(firstDay.getDate() - firstDay.getDay());
  
  // 获取日历网格结束日期（包含下个月的日期）
  const endDate = new Date(lastDay);
  endDate.setDate(lastDay.getDate() + (6 - lastDay.getDay()));
  
  const dates = [];
  const currentDateValue = new Date(startDate);
  
  while (currentDateValue <= endDate) {
    const dateObj = {
      key: currentDateValue.getTime(),
      day: currentDateValue.getDate(),
      date: new Date(currentDateValue),
      isCurrentMonth: currentDateValue.getMonth() === month,
      isToday: isToday(currentDateValue),
      hasAppointment: hasAppointmentOnDate(currentDateValue)
    };
    dates.push(dateObj);
    currentDateValue.setDate(currentDateValue.getDate() + 1);
  }
  
  return dates;
});

const selectedDateAppointments = computed(() => {
  if (!selectedDate.value) return [];
  
  return appointments.value.filter(app => {
    const appDate = new Date(app.date);
    return appDate.toDateString() === selectedDate.value!.toDateString();
  });
});

// 方法
const isToday = (date: Date) => {
  const today = new Date();
  return date.toDateString() === today.toDateString();
};

const hasAppointmentOnDate = (date: Date) => {
  return appointments.value.some(app => {
    const appDate = new Date(app.date);
    return appDate.toDateString() === date.toDateString();
  });
};

const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

const getAppointmentColor = (status: string) => {
  switch (status) {
    case '已确认':
      return 'success';
    case '待确认':
      return 'warning';
    case '已取消':
      return 'error';
    default:
      return 'grey';
  }
};

const previousMonth = () => {
  const newDate = new Date(currentDate.value);
  newDate.setMonth(newDate.getMonth() - 1);
  currentDate.value = newDate;
};

const nextMonth = () => {
  const newDate = new Date(currentDate.value);
  newDate.setMonth(newDate.getMonth() + 1);
  currentDate.value = newDate;
};

const selectDate = (dateObj: any) => {
  selectedDate.value = dateObj.date;
  showAppointmentDialog.value = true;
};

onMounted(() => {
  // 组件挂载后的初始化逻辑
  console.log('Calendar component mounted');
});
</script>

<style scoped>
.calendar-container {
  padding: 20px;
}

.calendar-grid {
  width: 100%;
}

.calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background-color: #f5f5f5;
  border-radius: 4px 4px 0 0;
}

.day-header {
  background-color: #e0e0e0;
  padding: 12px;
  text-align: center;
  font-weight: 600;
  font-size: 14px;
}

.calendar-body {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background-color: #f5f5f5;
  border-radius: 0 0 4px 4px;
}

.date-cell {
  background-color: white;
  padding: 12px;
  min-height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  transition: background-color 0.2s;
}

.date-cell:hover {
  background-color: #f0f0f0;
}

.date-cell.other-month {
  color: #bbb;
  background-color: #fafafa;
}

.date-cell.today {
  background-color: #e3f2fd;
  color: #1976d2;
  font-weight: 600;
}

.date-cell.has-appointment {
  border-left: 4px solid #1976d2;
}

.date-number {
  font-size: 16px;
  margin-bottom: 4px;
}

.appointment-indicator {
  position: absolute;
  top: 8px;
  right: 8px;
}
</style> 